Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies.
I love to learn new things in life that keep me motivated.
There are two ways to read and write files in Java:
Using the FileInputStream and FileOutputStream classes: These classes provide a low-level interface for reading and writing files.
Using the Scanner and PrintWriter classes: These classes provide a higher-level interface for reading and writing files.
Here is a sample code that shows how to read and write a file using the FileInputStream and FileOutputStream classes:
Java
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileIOExample
{
public static void main(String[] args) throws Exception
{
// Create a FileInputStream object for the file that we want to read.
FileInputStream inputStream = new FileInputStream("myfile.txt");
// Create a FileOutputStream object for the file that we want to write to.
FileOutputStream outputStream = new FileOutputStream("myfile_copy.txt");
// Read the contents of the file and write them to the new file.
int data;
while ((data = inputStream.read()) != -1)
{
outputStream.write(data);
}
// Close the streams.
inputStream.close();
outputStream.close();
}
}
Here is a sample code that shows how to read and write files using the Scanner and PrintWriter classes:
Java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileIOExample
{
public static void main(String[] args) throws FileNotFoundException
{
// Create a Scanner object for the file that we want to read.
Scanner scanner = new Scanner(new File("myfile.txt"));
// Create a PrintWriter object for the file that we want to write to.
PrintWriter writer = new PrintWriter("myfile_copy.txt");
// Read the contents of the file and write them to the new file.
while (scanner.hasNextLine())
{
writer.println(scanner.nextLine());
}
// Close the streams.
scanner.close();
writer.close();
}
}
Liked By
Write Answer
How to read and write files in Java? Please provide a sample.
Join MindStick Community
You have need login or register for voting of answers or question.
Aryan Kumar
06-Sep-2023There are two ways to read and write files in Java:
Here is a sample code that shows how to read and write a file using the FileInputStream and FileOutputStream classes:
Java
Here is a sample code that shows how to read and write files using the Scanner and PrintWriter classes:
Java